package gui;

import java.awt.*;
import java.awt.event.*;

import javax.swing.JPanel;

public class MyCanvas extends JPanel {
	private static final long serialVersionUID = 1L;

	public int GRID = 32;
	public double SNAP_RADIUS = 8;
	public int TICK = 1;
	public boolean showGrid = false;

	private MainFrame mainFrame;
	private MyView v;
	protected UI_SFG graph;
	private Tool tool;

	public MyCanvas(MainFrame f) {
		setSize(400, 400);
		this.mainFrame = f;
		graphClear();
		setTool(new ToolNull());
		v = new MyView(this);
		v.setZ(1);
		addListeners();
	}

	private void addListeners() {
		setFocusable(true);
		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				try {
					tool().mouseClick(mainFrame, graph, e, v);
				} catch (Exception ex) {
					mainFrame.error("Error!");
				}
				repaint();
			}
		});
		addMouseMotionListener(new MouseAdapter() {
			MouseEvent ePrev = null;

			@Override
			public void mouseMoved(MouseEvent e) {
				int dX = 0, dY = 0;
				if (ePrev != null) {
					dX = e.getX() - ePrev.getX();
					dY = e.getY() - ePrev.getY();
				}
				try {
					tool().mouseMove(mainFrame, graph, e, dX, dY, v);
				} catch (Exception ex) {
					mainFrame.error("Error!");
				}
				repaint();
				ePrev = e;
			}

			@Override
			public void mouseDragged(MouseEvent e) {
				int dX = 0, dY = 0;
				if (ePrev != null) {
					dX = e.getX() - ePrev.getX();
					dY = e.getY() - ePrev.getY();
				}
				try {
					tool().mouseDrag(mainFrame, graph, e, dX, dY, v);
				} catch (Exception ex) {
					mainFrame.error("Error!");
				}
				repaint();
				ePrev = e;
			}
		});
	}

	@Override
	public void paint(Graphics g) {
		// BACKGROUND
		g.setColor(getBackground());
		g.fillRect(0, 0, getWidth(), getHeight());
		Graphics2D g2 = (Graphics2D) g;
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		if (showGrid)
			drawGrid(g2);
		// GRAPH
		graph.paint(g2, v);
		// TOOL
		try {
			tool().paint(mainFrame, graph, g2, v);
		} catch (Exception ex) {
			mainFrame.error("Error!");
		}
		setCursor(tool.cursor());
	}

	private void drawGrid(Graphics2D g2) {
		g2.setColor(getBackground().darker());
		for (int y = 0; y <= getHeight() / GRID; y++)
			for (int x = 0; x <= getWidth() / GRID; x++)
				Draw.crossHair(g2, x * GRID, y * GRID, TICK, true, false);
	}

	public Tool tool() {
		return tool;
	}

	public void setTool(Tool tool) {
		this.tool = tool;
		tool.select(mainFrame);
	}

	public void graphClear() {
		graph = new UI_SFG();
	}

}
